import org.junit.Test;

import java.io.UnsupportedEncodingException;

public class StringConstructor {
    @Test
    public void test() {
        String s1 = new String("ab");
        String s2 = new String(new char[]{'a', 'b'});
        System.out.println(s2);
        System.out.println(s1 == s2);
    }

    @Test
    public void test1() {
        //基本数据类型转字符串
        int num = 10;
        String s1 = num + "";
        String s2 = String.valueOf(num);
        //字符串转基本数据类型
        String s4 = "123";
        int s5 = Integer.parseInt(s4);
        System.out.println(s5);
    }
    @Test
    public void test2() {
        String str = "hello";
        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);

        }
    }

    @Test
    public void test3() throws UnsupportedEncodingException {
        String str = new String("abc");
        //如果使用中文，则自动转换utf-8，汉字一个占三个字节，gbk占2个，都向下兼容ASCII码
//        String str = new String("abc中国");
        byte[] bytes = str.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        System.out.println("---------------------");
        byte[] bytes2 = str.getBytes("gbk");
        for (int i = 0; i < bytes2.length; i++) {
            System.out.println(bytes2[i]);
        }

        //字节转换为字符串，这里必须使用相同的字符集，不然会乱码
        System.out.println("****************************");
        String str2 = new String(bytes,"gbk");
        System.out.println(str2);
    }
}
